package com.farmlei.zkt_c3100.lock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 门禁刷卡事件监听器
 * @author farmlei
 * @since 2018/10/4
 */
public class DoorRecordListener {
    private static Logger logger = LoggerFactory.getLogger(DoorRecordListener.class);

    private DoorRecordListener() {
        listenLastedRecord();
    }
    private static DoorRecordListener doorRecordListener = null;
    public static DoorRecordListener getInstance() {
        if (doorRecordListener == null) {
            doorRecordListener = new DoorRecordListener();
        }
        return doorRecordListener;
    }

    public void init() {
        System.out.println("初始化门禁监听成功");
    }

    /**
     * 启动线程，以轮询的方式监听最新的刷卡记录
     */
    private void listenLastedRecord() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    try {
                        ZktecoUtil.getLatestRecordsAndOpenDoor();
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }

                    //间隔1000毫秒轮询一次
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });
        thread.start();
    }
}
